const { Service } = require("egg");
const { Op } = require("sequelize");

class UserService extends Service {

  async createUser(user) {
    const { ctx } = this;
    const data = await ctx.model.User.create(user);
    return await this.getUser({ id: data.id });
  }

  async updateUser(where, updates) {
    const user = await this.ctx.model.User.findOne({ where: where, });
    if (user) {
      Object.assign(user, updates);
      await user.save();
      return await this.getUser({ id: user.id });
    } else {
      return 0;
    }
  }

  async getUser(where) {
    const { ctx } = this;
    try {
      const res = await ctx.model.User.findOne({
        where: {
          ...where,
        },
        attributes: {
          exclude: ["password"],
        }
      })
      let data = res ? res.toJSON() : res;
      return data;
     
    } catch (error) {

      throw new Error(error);
    }
  }

  async list(query) {
    const { pageNum = 1, pageSize = 10, account, type = 'normal' } = query; // 默认值设置
    const offset = (pageNum - 1) * pageSize;
    const { ctx } = this;
    const order = [["updatedAt", "DESC"]];
    const where = {
      isDeleted: 0,
      type
    };
    if (account) {
      where.account = {
        [Op.like]: `%${account}%`,
      };
    }
    const users = await ctx.model.User.findAll({
      raw: true,
      where,
      limit: parseInt(pageSize),
      offset: parseInt(offset),
      order,
    });
    const total = await ctx.model.User.count({ where });

    const hasNextPage = offset + pageSize < total;
    const response = {
      sorts: users,
      total,
      pageNum: parseInt(pageNum),
      pageSize: parseInt(pageSize),
      hasNextPage,
    };

    return response;
  }

  async findUsersByIds(ids) {
    const { ctx } = this;
    const users = await ctx.model.User.findAll({
      where: {
        id: {
          [Op.in]: ids, // 使用Op.in操作符来匹配ID列表
        },
        isDeleted: 0, // 只查找未删除的用户
      },
      attributes: { exclude: ["password"] },
      raw: true, // 返回原始数据
    });
    return users;
  }
}

module.exports = UserService;
